package com.study.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;
import java.util.Set;

public class MyBeanUtils {

    public static <T> T copyToBean(HttpServletRequest request, Class<T> clazz) {
        try {
            //注册不抛出异常、Integer默认值为null，否则为0
            boolean throwException=false;
            boolean defaultNull=true;
            int defaultArraySize=0;
            BeanUtilsBean.getInstance().getConvertUtils().register(throwException,  defaultNull, defaultArraySize);
            // （注册日期类型转换器）
            DateConverter converter = new DateConverter(null);
            converter.setPattern(new String("yyyy-MM-dd HH:mm:ss"));
            ConvertUtils.register(converter, Date.class);
            // 创建对象
            T t = clazz.newInstance();
            BeanUtils.populate(t, request.getParameterMap());
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static <T> T copyToBean1(HttpServletRequest request, Class<T> clazz) {
        try {
            T obj = clazz.getDeclaredConstructor().newInstance();
            //获取参数  ?title=aaaa&content=xxxxxx&xx=yyyy
            Map<String, String[]> paramMap = request.getParameterMap();
            //遍历Map
            Set<Map.Entry<String, String[]>> set = paramMap.entrySet();
            for (Map.Entry<String, String[]> entry : set) {
                String name = entry.getKey();  //属性名
                String[] value = entry.getValue();
                try {
                    //根据属性名获取setter方法  title----setTitle()
                    String setName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);  //setName = "setTitle";
                    Class<?> type = clazz.getDeclaredField(name).getType();  //获取对应的属性的类型
                    // 方法名  参数类型
                    Method method = clazz.getDeclaredMethod(setName, type);
                    // obj.setTitle(value);
                    Object val = value[0];
                    // 转型问题：
                    if (type == int.class || type == Integer.class) {
                        val = Integer.parseInt(val.toString());
                    } else if (type == float.class || type == Float.class) {
                        val = Float.parseFloat(val.toString());
                    }
                    //obj.setTitle(value);
                    method.invoke(obj, val);
                } catch (Exception e) {

                }
            }
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
